package com.juyu.miliao.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.juyu.miliao.api.dao.mysql.EnergyLevelDao;
import com.juyu.miliao.api.domain.Appkey;
import com.juyu.miliao.api.domain.EnergyLevel;
import com.juyu.miliao.api.domain.User;
import com.juyu.miliao.api.domain.dto.IntegralLevelAndTitleDTO;
import com.juyu.miliao.api.domain.dto.UserInfoDistanceDTO;
import com.juyu.miliao.api.domain.vo.HostUserLevelVo;
import com.juyu.miliao.api.domain.vo.UserStatusVO;
import com.juyu.miliao.api.exception.NotVipException;
import com.juyu.miliao.api.service.*;
import com.juyu.miliao.api.util.HostUserLevelUtil;
import com.juyu.miliao.api.util.JacksonView;
import com.juyu.miliao.api.validator.UpdateUserInfoCheck;
import com.juyu.miliao.common.constant.PageConstant;
import com.juyu.miliao.common.constant.PhoneSystemConstant;
import com.juyu.miliao.common.domain.CommonHead;
import com.juyu.miliao.common.domain.OpenApiStatus;
import com.juyu.miliao.common.domain.PageIndex;
import com.juyu.miliao.common.domain.Subject;
import com.juyu.miliao.common.exception.ConsumeRuntimeException;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.util.CommonUtil;
import com.juyu.miliao.common.util.PageInfoUtil;
import com.juyu.miliao.common.util.ServletTool;
import com.juyu.miliao.common.util.VerifyUtil;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/userInfo")
@Slf4j
public class UserInfoController {
    public static final String  HOST_LOCATION_STAR = "hostLocationStar";
    @Resource
    UserInfoService userInfoService;
    @Resource
    private OpenApiService openApiService;
    @Resource
    private AppKeyService appkeyService;
    @Resource
    private VersionHistoryService versionHistoryService;
    @Resource
    private EnergyLevelService energyLevelService;
    @Resource
    private IntegralLevelInfoService integralLevelInfoService;
    @Resource
    private IconOfficialService iconOfficialService;
    @Resource
    private EnergyLevelDao energyLevelDao;

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 首页- 用户豪列表(非主播用户列表),只有主播能够查看该列表
     *
     * @param type 分类：1所用，2在线用户
     * @return
     */
    @GetMapping("/commonUserList/{type:^[1-9][0-9]*$}/{page}-{pageSize}")
    @JsonView(JacksonView.CommonSortUser.class)
    public List<User> getCommonUserList(@PathVariable("type") Integer type, @PathVariable("page") Integer page,
                                        @PathVariable("pageSize") Integer pageSize) {
        if (type != 1 && type != 2)
            throw new IllegalParamException("参数错误：type错误");
        if (page <= 0) {
            page = 1;
        }
        if (pageSize <= 0) {
            pageSize = 20;
        }
        List<User> list = new ArrayList<User>();
        if (type == 1) {
            list = userInfoService.getCommonUserList(page, pageSize);
        } else {
            list = userInfoService.getCommonOnLineList(page, pageSize);
        }
        return list;
    }

    /**
     * miLiao1.2新需求- 用户豪列表(非主播用户列表)
     * 该列表只显示男性用户
     * 排序优先空闲、繁忙、勿扰、离线，其次各个状态中用户根据等级排序
     */
    @GetMapping("/commonHavingList/{page}")
    @JsonView(JacksonView.CommonSortUser.class)
    public List<User> getCommonHavingList(@PathVariable("page") Integer page) {
        if (page <= 0) {
            page = 1;
        }
        int pageSize = 20;
        return userInfoService.getCommonHavingList(page, pageSize);
    }

    /**
     * 发现- 优质主播列表
     *
     * @param type 分类：1优质主播列表-最热，2最新主播列表-最新，3密先生，4 在线男女用户, 5颜值, 6蜜桃,7萌新,8壕友
     */
    @CrossOrigin
    @GetMapping("/qualityHostList/{type:^[1-9][0-9]*$}/{page}-{pageSize}")
    @JsonView(JacksonView.QualityHost.class)
    public List<User> getQualityHostList(@PathVariable("type") Integer type,
                                         @PathVariable("page") Integer page,
                                         @PathVariable("pageSize") Integer pageSize,
                                         Authentication token,
                                         HttpServletRequest request) {

        if (type <1 || type >8)
            throw new IllegalParamException("参数错误：type错误");
        if (page <= 0) {
            page = 1;
        }
        pageSize = 20;
        List<User> list = new ArrayList<User>();
        CommonHead com = VerifyUtil.verifyCommonHead(request);
        //是否正在审核
        OpenApiStatus ops = openApiService.getOpenApi(com);
        User userInfo = new User();
        if(token != null){
            Subject subject = (Subject) token.getPrincipal();
            userInfo = userInfoService.getUserInfoById((int) subject.getId());
        }

        if (ops != null && ops.getForwardAudit() && ops.getBackAudit()) {
            String appUserList = "";
            if (type == 1) {
                appUserList = appkeyService.getAppKeyByKey("qualityHostList_hot").getValue();
            }else if (type == 2){
                appUserList = appkeyService.getAppKeyByKey("qualityHostList_new").getValue();
            }else if (type == 3){
                appUserList = appkeyService.getAppKeyByKey("qualityHostList_man").getValue();
            }else if (type == 4){
                appUserList = appkeyService.getAppKeyByKey("qualityOnLineList_sex").getValue();
            }else {
                return list;
            }
            try {
                list = JSONArray.parseArray(appUserList, User.class);
            } catch (Exception e) {
                log.error("发现- 优质主播列表审核包假数据转换失败:e={}", e.getMessage());
            }
            //加一个分页 超出返回空
            PageIndex pageIndex = PageInfoUtil.getPageIndex(page, pageSize, list.size(), false);
            int offset = pageIndex.getOffset();
            if (offset == PageConstant.OUT_OF_ROWS) {
                return new ArrayList<>();
            }
            if ((offset + pageSize) > list.size()) {
                return list.subList(offset, list.size());
            }
            return list.subList(offset, (offset + pageSize));
        } else {
            switch (type){
                case 1 :
                    if(userInfo == null){
                        throw new ConsumeRuntimeException("用户没有登录");
                    }
                    list = userInfoService.getQualityHostList(userInfo.getUserId(),page, pageSize);
                    break;
                case 2 :
                    list = userInfoService.getNewQualityHostList(page, pageSize,request);
                    break;
                case 3 :
                    list = userInfoService.getManHostList(page, pageSize);
                    break;
                case 4 :
                    if(userInfo == null){
                        throw new ConsumeRuntimeException("用户没有登录");
                    }
                    list = userInfoService.getOnLineUsersList(userInfo.getSex(),page,pageSize);
                    break;
                case 5 :
                    list = userInfoService.getBeautyHostList(page,pageSize);
                    break;
                case 6 :
                    list = userInfoService.getFigureHostList(page,pageSize);
                    break;
                case 7 :
                    list = userInfoService.getOnlineThreeDaysNewUserList(page,pageSize);
                    break;
                case 8 :
                    if(userInfo == null){
                        throw new ConsumeRuntimeException("用户没有登录");
                    }
                    if(userInfo.getIsHost()!=1){
                        throw new ConsumeRuntimeException("用户不是主播");
                    }
                    IntegralLevelAndTitleDTO userIntegralLevel = integralLevelInfoService.
                            getUserIntegralLevel(userInfo.getIntegralSum());
                    if(userIntegralLevel.getIntegralGrade()<6){
                        JSONObject json = new JSONObject();
                        IntegralLevelAndTitleDTO level = integralLevelInfoService.getIntegralLevelAndTitleDTO(6);
                        if(level!=null){
                            json.put("pic",level.getIntegralGradePic());
                        }else{
                            json.put("pic","");
                        }
                        json.put("desc","该内容值针对6级以上的主播开放，请加油升级哦~");
                        throw new ConsumeRuntimeException(json.toString());
                    }
                    list = userInfoService.getOnlineRechargeAmountUser(page,pageSize);
                    break;
            }
        }
        return list;
    }

    /**
     * 我的-编辑个人资料-获取用户个人信息
     *
     * @param
     * @return
     */
    @GetMapping("/{id:^[1-9][0-9]*$}")
    public User getUserInfoById(HttpServletRequest request,
                                Authentication token, @PathVariable("id") long id) {
        JSONObject json = new JSONObject();
        Subject subject = (Subject) token.getPrincipal();
//        String enable = userLoginDao.selectUserLoginByIdForEnable(id);
//        if(StringUtils.isNotBlank(enable) &&"2".equals(enable)){
//               throw new ConsumeRuntimeException(VIOLATION_MSG);
//        }

        User user = userInfoService.getUserInfoById(id, subject.getId());

        /* 1.4.2 ios需求 用户个人信息增加是否审核开关*/
        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        String versionNum = commonHead.getVersionNum();
        int phoneSystem = CommonUtil.null2Int(commonHead.getPhoneSystem());
        String channel = commonHead.getChannel();
        String appPackageId = commonHead.getAppPackageId();
        String[] ids = versionNum.split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        String ip = ServletTool.getRemoteHost(request);
        Boolean isAudit =false;
        if (phoneSystem == PhoneSystemConstant.ANDROID || phoneSystem == PhoneSystemConstant.IOS) {
            isAudit = versionHistoryService
                    .compareVersion(ip,ids, phoneSystem, channel, appPackageId, versionNum)
                    .getIsAudit();
        }
        user.setCmsSw(isAudit);
        EnergyLevel energyLevel = energyLevelService.getUserEnergyLevel(user.getEnergySum());
        List<EnergyLevel> energyLevelList = energyLevelDao.getUserEnergyLevelList();
        for(EnergyLevel e: energyLevelList){
            if(e.getLevelId()==user.getVehicleId()){
                energyLevel.setVehicleName(e.getVehicleName());
                energyLevel.setVehiclePic(e.getVehiclePic());
                energyLevel.setVehicleVideo(e.getVehicleVideo());
            }
        }
        user.setEnergyLevel(energyLevel);
        IntegralLevelAndTitleDTO userIntegralLevel = integralLevelInfoService.getUserIntegralLevel(user.getIntegralSum());
        userInfoService.updateUserVideoPrice(user,userIntegralLevel);
         HostUserLevelVo hostUserLevel = HostUserLevelUtil.getHostUserLevel(userIntegralLevel);
        user.setHostUserLevelVo(hostUserLevel);
        return user;
    }

    /**
     * 1.5.2 用户修改头像
     * @param token
     * @param iconUrl
     * @param iconType
     * @param iconId
     */
    @PostMapping("updateIcon")
    public void updateIcon(Authentication token,
                           @RequestParam("iconUrl")String iconUrl,
                           @RequestParam("iconType")int iconType,
                           @RequestParam("iconId")Integer iconId){
        Subject subject = (Subject) token.getPrincipal();
        int userIcon =0;
        if(!iconId.equals("0")){
            userIcon =iconId;
        }
        iconOfficialService.updateIcon(subject.getId(),iconUrl,iconType,userIcon);
    }

    /**
     * 帮助ios修改bug userInfo/{id},如果没有id则 返回当前登录用户个人资料
     */
    @GetMapping()
    public User getUserInfoByMe(Authentication token) {
        Subject subject = (Subject) token.getPrincipal();
        return userInfoService.getUserInfoById(subject.getId(), subject.getId());
    }

    /**
     * 我的-编辑个人资料-保存修改
     *
     * @param
     * @return
     */
    @PatchMapping()
    public void updateUserInfo(Authentication token, @Validated(UpdateUserInfoCheck.class) User entity) {
        Subject subject = (Subject) token.getPrincipal();
        if (subject.getId() != entity.getUserId()) {
            throw new IllegalParamException("用户id错误");
        }
        User user = new User();
        user = entity;
        userInfoService.updateUserInfo(user);
    }

    /**
     * 清空语音签名，语音签名时长
     *
     * @param token
     * @param
     */
    @PatchMapping("/clean")
    public void updateCleanUserInfo(Authentication token, @Validated(UpdateUserInfoCheck.class) User entity) {
        Subject subject = (Subject) token.getPrincipal();
        if (subject.getId() != entity.getUserId())
            throw new IllegalParamException("用户id错误");
        User user = new User();
        user = entity;
        userInfoService.updateCleanUserInfo(user);
    }

    /**
     * 1.4.3需求 更新语音介绍
     * @param token
     * @param voiceSignature
     */
    @PatchMapping("/replaceVoice")
    public void updateUserVoiceSignature(Authentication token,@RequestParam String voiceSignature,
                                         @RequestParam String voiceSignatureTime){
        Subject subject = (Subject) token.getPrincipal();

        userInfoService.updateUserVoiceSignature(subject.getId(),voiceSignature,voiceSignatureTime);
    }

    /**
     * 用户是否接听通话
     *
     * @param type   1:接通成功，2:接通失败
     * @param userId
     */
    @GetMapping("/callSum/{userId}/{type}")
    public void addUserCallSum(@PathVariable("type") Integer type, @PathVariable("userId") Integer userId) {
//        if (type != 1 && type != 2)
//            throw new IllegalParamException("参数错误：type不能为0");
//        if (userId == 0)
//            throw new IllegalParamException("参数错误：type不能为0");
//        userInfoService.addUserCallSum(type, userId);
    }

    /**
     * 获取用户状态
     *
     * @param userId userId
     * @return UserStatusVO
     */
    @GetMapping(value = "/{userId}/status")
    public UserStatusVO getUserStatusVO(HttpServletRequest request,@PathVariable Long userId) {
        UserStatusVO userStatusVo = userInfoService.getUserStatusVO(userId);
        /* 1.4.2 ios需求 用户个人信息增加是否审核开关*/
        CommonHead commonHead = VerifyUtil.verifyCommonHead(request);
        String versionNum = commonHead.getVersionNum();
        int phoneSystem = CommonUtil.null2Int(commonHead.getPhoneSystem());
        String channel = commonHead.getChannel();
        String appPackageId = commonHead.getAppPackageId();
        String[] ids = versionNum.split("\\.");
        if (ids.length < 3) {
            throw new IllegalParamException("版本参数错误");
        }
        String ip = ServletTool.getRemoteHost(request);
        Boolean isAudit =false;
        if (phoneSystem == PhoneSystemConstant.ANDROID || phoneSystem == PhoneSystemConstant.IOS) {
            isAudit = versionHistoryService
                    .compareVersion(ip,ids, phoneSystem, channel, appPackageId, versionNum)
                    .getIsAudit();
        }
        userStatusVo.setCmsSw(isAudit);
        return userStatusVo;
    }

	/**
	 * 设为封面
	 * @param token
	 * @param userCoverUrl
	 */
	@PutMapping("/userCoverUrl")
	 public void updateUserCoverUrl(Authentication token,String userCoverUrl){
		 Subject subject = (Subject) token.getPrincipal();
        userInfoService.updateUserCoverUrl( subject.getId(),userCoverUrl);
	 }

    /**
     * 1.4.3 需求 个人页面之资料页
     * @param token
     * @return
     */
    @GetMapping("/hostUserMaterial/{userId}")
	 public JSONObject getHostUserMaterial(Authentication token,@PathVariable("userId") long userId){
         Subject subject = (Subject) token.getPrincipal();
        return userInfoService.getHostUserMaterial( subject.getId(),userId);
     }

    /**
     * 寻寻1.5.1 发现列表
     *  查询在线主播
     *  大于等于5等级的主播随机两个
     *  小于5等级主播 随机两个
     * @return
     */
     @PostMapping("/discoveryHost")
     public JSONObject getHostList(HttpServletRequest request){
         return userInfoService.getHostUser(request);
     }

    /**
     * 寻寻1.5.1 关注列表
     * 获取全部关注列表（不分页）
     * 列表排序（在线>主播等级(降序)>魅力等级(降序)>关注时间(降序)）
     * 在线状态：在线（1）> 繁忙 (2) > 离线(0) > 封号（4）
     * @param token
     * @return
     */
     @GetMapping("/followHost")
     public List<User> getFollowHostUser(Authentication token){
         Subject subject = (Subject) token.getPrincipal();
         User user = userInfoService.getUserInfoById(Integer.parseInt(subject.getId()+""));
         if(user.getIsHost()==1){
             return userInfoService.getFollowHostUserList(subject.getId());
         }else{
             return userInfoService.getFollowHostUserListByUser(subject.getId());
         }

     }

    /**
     * 寻寻1.5.1 安卓版热门列表
     * 查询在线女主播（不分页）
     * 排序规则:
     * （在线>主播等级(降序)>魅力等级(降序)）
     * @return
     */
    @GetMapping("/hostUserList")
    @JsonView(JacksonView.HomePageHostList.class)
    public List<User> getLineHostUser(HttpServletRequest request){
        return userInfoService.getLineHostUserList(request);
    }

    /**
     * 1.5.3 主播30天新人列表
     * @return
     */
    @GetMapping("/thirtyDaysNewHostList")
    @JsonView(JacksonView.HomePageHostList.class)
    public List<User> getThirtyDaysNewHostList(HttpServletRequest request){
        return userInfoService.getNewQualityHostList(0,0,request);
    }

    /**
     * 附近列表
     * 开启定位展示最近的在线主播4个
     * 不开定位随机展示在线主播4个
     * @param location 经纬度 格式：纬度(lat),经度(lon)
     * @return
     */
    @GetMapping("/hostUserDistanceList")
    public List<UserInfoDistanceDTO> getDistanceHostUser(@RequestParam(required = false) String location,
                                                         HttpServletRequest request,
                                                         Authentication token){
        Subject subject = (Subject) token.getPrincipal();
        User user = userInfoService.getUserInfoById(subject.getId(),subject.getId());
        if(user.getIsVip() != 1 && user.getIsSvip()!=1 && user.getIsPlatinumVip()!=1){
            throw new NotVipException();
        }
        List<UserInfoDistanceDTO> distanceHostUserList = new ArrayList<>();
        if(!StringUtils.isEmpty(location)){
            distanceHostUserList = userInfoService.getDistanceHostUserList(location,request);
        }else {
            distanceHostUserList =  userInfoService.getDistanceHostUserList(null,request);
        }
        return distanceHostUserList;
    }
    /**
     * 附近列表(安卓)
     * 开启定位展示所有在线有位置的女主播
     * 不开定位随机展示在线所有女主播
     * @param location 经纬度 格式：纬度(lat),经度(lon)
     * @return
     */
    @GetMapping("/azd/hostUserDistanceList")
    public List<UserInfoDistanceDTO> getDistanceHostUserforAndroid(
            @RequestParam(required = false) String location,
            HttpServletRequest request,
            Authentication token){
        Subject subject = (Subject) token.getPrincipal();
        User user = userInfoService.getUserInfoById(subject.getId(),subject.getId());
        if(user.getIsVip() != 1 && user.getIsSvip()!=1 && user.getIsPlatinumVip()!=1){
            throw new NotVipException();
        }
        List<UserInfoDistanceDTO> distanceHostUserList = new ArrayList<>();
        if(!StringUtils.isEmpty(location)){
            distanceHostUserList = userInfoService.getDistanceHostUserListForAndroid(location,request);
        }else {
            distanceHostUserList =  userInfoService.getDistanceHostUserListForAndroid(null,request);
        }
        return distanceHostUserList;
    }

    /**
     * 主播修改地理位置
     * @param location，经纬度 格式：纬度(lat),经度(lon)
     */
    @PostMapping("/host/update/location")
    public void updateLocation(Authentication token,String location) throws Exception {
        if(StringUtils.isEmpty(location)){
            throw new ConsumeRuntimeException("经纬度不能为空");
        }
        Subject subject = (Subject) token.getPrincipal();
        Appkey appkey =appkeyService.getAppKeyByKey(HOST_LOCATION_STAR);

        userInfoService.updateHostLocation(appkey,subject.getId(),location);

    }

    /**
     * 实时更新主播地理位置接口
     * @param token
     * @param location
     * @throws Exception
     */
    @PostMapping("/host/update/realTimeLocation")
    public void updateHostRealTimeLocation(Authentication token,String location) throws Exception {
        if(!StringUtils.isEmpty(location)){
            Subject subject = (Subject) token.getPrincipal();
            userInfoService.updateHostRealTimeLocation(subject.getId(),location);
        }
    }

    /**
     * 获取登录用户名
     */
    @GetMapping("/phone")
    public JSONObject getUserLoginByUserId(Authentication token){
        Subject subject = (Subject) token.getPrincipal();
        return userInfoService.getPhoneByUserId(subject.getId());
    }

//    /**
//     *  1.5.2 用户获取个人信息
//     * @param token
//     * @return
//     */
//    @GetMapping("/ordinaryUser/{id:^[1-9][0-9]*$}")
//    public JSONObject getUserByUserId(HttpServletRequest request,
//                                      Authentication token, @PathVariable("id") long userId){
//        Subject subject = (Subject) token.getPrincipal();
//        return userInfoService.getUserByUserId(subject.getId(),userId,request);
//    }

    @PostMapping("/update/vehicle")
    public void updateUserVehicleId(Authentication token,int vehicleId){
        Subject subject = (Subject) token.getPrincipal();
        userInfoService.updateUserVehicleId(subject.getId(),vehicleId);
    }

//    /**
//     * 用户修改昵称
//     * @param token
//     * @param niceName
//     */
//    @PostMapping("/niceName")
//    public void updateUserNameByUserName(Authentication token,@RequestParam("niceName")String niceName){
//        Subject subject = (Subject) token.getPrincipal();
//        userInfoService.updateUserNameByUserName(subject.getId(),niceName);
//    }


    /**
     * 2.0主播端 我的等级之主播信息
     * @param token
     * @return
     */
    @GetMapping("/hostUserLevel")
    public JSONObject getHostUserLevel(Authentication token){
         Subject subject = (Subject) token.getPrincipal();
        return userInfoService.getHostUserLevel(subject.getId());

    }


    @GetMapping("/check/phone/{phoneNum}")
    public void checkPhone(@PathVariable("phoneNum") String phoneNum){
        String phoneRegex="^[0-9]{11}$";

        if(phoneNum == null || !phoneNum.matches(phoneRegex)) {
            throw new ConsumeRuntimeException("手机号格式不正确");
        }
        userLoginService.checkPhone(phoneNum);
    }

    /**
     * 获取主播最新动态
     * @param userId
     * @return
     */
    @GetMapping("hostRecentDevelopments/{userId}")
    public Map<String,Object> getHostRecentDevelopmentsList(@PathVariable("userId") Long userId) throws IOException {
        if(userId==null){
            throw new ConsumeRuntimeException("主播id不能为空");
        }
        Map<String,Object> map = userInfoService.getHostRecentDevelopmentsList(userId);
        return map;
    }

    /**
     * 1.5.5 用户是否是首冲用户
     * @param token
     * @return
     */
    @GetMapping("/first/recharge")
    public JSONObject getIsMemberFirstRechargeUser(Authentication token){
        Subject subject = (Subject) token.getPrincipal();
        return userInfoService.getIsMemberFirstRechargeUser(subject.getId());
    }

    @PostMapping("/host/isLine")
    public JSONArray getHostIsLine(String hostUserIdArray){
        return userInfoService.getHostIsLine(hostUserIdArray);
    }
}
